/**
 * 点赞路由处理模块
 * @author HalRui
 * @version 1.0.0
 * @description 处理点赞、取消点赞、点赞统计等相关API路由
 * @date 2025年9月27日
 */

const express = require('express');
const router = express.Router();
const likesAPI = require('../../libs/likes-api');
const STATUS_CODES = require('../../utils/status-codes');

/**
 * @route POST /likes/toggle
 * @description 点赞或取消点赞
 * @body {number} userId - 用户ID
 * @body {string} targetType - 目标类型（video/comment）
 * @body {number} targetId - 目标ID
 * @body {number} likeStatus - 点赞状态（1: 点赞, -1: 点踩），默认1
 * @body {string} ip - IP地址（可选）
 */
router.post('/toggle', async (req, res) => {
    try {
        const { userId, targetType, targetId, likeStatus = 1, ip = '' } = req.fields;

        // 参数验证
        if (!userId || !targetType || !targetId) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "用户ID、目标类型和目标ID不能为空"
            });
        }

        // 类型转换和验证
        const userIdNum = parseInt(userId);
        const targetIdNum = parseInt(targetId);
        const likeStatusNum = parseInt(likeStatus);

        if (isNaN(userIdNum) || isNaN(targetIdNum)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "用户ID和目标ID必须为数字"
            });
        }

        if (!['video', 'comment'].includes(targetType)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "目标类型必须为video或comment"
            });
        }

        if (![1, -1].includes(likeStatusNum)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "点赞状态必须为1（点赞）或-1（点踩）"
            });
        }

        const result = await likesAPI.toggleLike(userIdNum, targetType, targetIdNum, likeStatusNum, ip);

        if (!result.success) {
            return res.json({
                code: STATUS_CODES.OPERATION_FAILED.code,
                message: result.message
            });
        }

        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: result.message,
            data: {
                action: result.action,
                like: result.data
            }
        });
    } catch (error) {
        res.json({
            code: STATUS_CODES.SERVER_ERROR.code,
            message: "点赞操作失败：" + error.message
        });
    }
});

/**
 * @route GET /likes/status/:userId/:targetType/:targetId
 * @description 获取点赞状态
 * @param {number} userId - 用户ID
 * @param {string} targetType - 目标类型
 * @param {number} targetId - 目标ID
 */
router.get('/status/:userId/:targetType/:targetId', async (req, res) => {
    try {
        const { userId, targetType, targetId } = req.params;

        // 类型转换和验证
        const userIdNum = parseInt(userId);
        const targetIdNum = parseInt(targetId);

        if (isNaN(userIdNum) || isNaN(targetIdNum)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "用户ID和目标ID必须为数字"
            });
        }

        if (!['video', 'comment'].includes(targetType)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "目标类型必须为video或comment"
            });
        }

        const result = await likesAPI.getLikeStatus(userIdNum, targetType, targetIdNum);

        if (!result.success) {
            return res.json({
                code: STATUS_CODES.OPERATION_FAILED.code,
                message: result.message
            });
        }

        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: "获取点赞状态成功",
            data: {
                status: result.status,
                isLiked: result.isLiked,
                isDisliked: result.isDisliked,
                like: result.data
            }
        });
    } catch (error) {
        res.json({
            code: STATUS_CODES.SERVER_ERROR.code,
            message: "获取点赞状态失败：" + error.message
        });
    }
});

/**
 * @route POST /likes/batch-status
 * @description 批量获取点赞状态
 * @body {number} userId - 用户ID
 * @body {string} targetType - 目标类型
 * @body {Array} targetIds - 目标ID数组
 */
router.post('/batch-status', async (req, res) => {
    try {
        const { userId, targetType, targetIds } = req.fields;

        // 参数验证
        if (!userId || !targetType || !targetIds) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "用户ID、目标类型和目标ID列表不能为空"
            });
        }

        // 类型转换
        const userIdNum = parseInt(userId);
        let targetIdsArray;

        try {
            targetIdsArray = Array.isArray(targetIds) ? targetIds : JSON.parse(targetIds);
        } catch (e) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "目标ID列表格式错误"
            });
        }

        if (isNaN(userIdNum) || !Array.isArray(targetIdsArray)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "参数格式错误"
            });
        }

        if (!['video', 'comment'].includes(targetType)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "目标类型必须为video或comment"
            });
        }

        const targetIdsNum = targetIdsArray.map(id => parseInt(id)).filter(id => !isNaN(id));

        const result = await likesAPI.batchGetLikeStatus(userIdNum, targetType, targetIdsNum);

        if (!result.success) {
            return res.json({
                code: STATUS_CODES.OPERATION_FAILED.code,
                message: result.message
            });
        }

        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: "批量获取点赞状态成功",
            data: {
                statusMap: result.statusMap,
                statusList: result.statusList
            }
        });
    } catch (error) {
        res.json({
            code: STATUS_CODES.SERVER_ERROR.code,
            message: "批量获取点赞状态失败：" + error.message
        });
    }
});

/**
 * @route GET /likes/stats/:targetType/:targetId
 * @description 获取目标的点赞统计
 * @param {string} targetType - 目标类型
 * @param {number} targetId - 目标ID
 */
router.get('/stats/:targetType/:targetId', async (req, res) => {
    try {
        const { targetType, targetId } = req.params;

        // 类型转换和验证
        const targetIdNum = parseInt(targetId);

        if (isNaN(targetIdNum)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "目标ID必须为数字"
            });
        }

        if (!['video', 'comment'].includes(targetType)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "目标类型必须为video或comment"
            });
        }

        const result = await likesAPI.getLikeStats(targetType, targetIdNum);

        if (!result.success) {
            return res.json({
                code: STATUS_CODES.OPERATION_FAILED.code,
                message: result.message
            });
        }

        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: "获取点赞统计成功",
            data: result.stats
        });
    } catch (error) {
        res.json({
            code: STATUS_CODES.SERVER_ERROR.code,
            message: "获取点赞统计失败：" + error.message
        });
    }
});

/**
 * @route GET /likes/history/:userId
 * @description 获取用户的点赞历史
 * @param {number} userId - 用户ID
 * @query {string} targetType - 目标类型（可选）
 * @query {number} page - 页码，默认1
 * @query {number} limit - 每页数量，默认20
 */
router.get('/history/:userId', async (req, res) => {
    try {
        const { userId } = req.params;
        const { targetType, page = 1, limit = 20 } = req.query;

        // 类型转换
        const userIdNum = parseInt(userId);
        const pageNum = parseInt(page);
        const limitNum = parseInt(limit);

        if (isNaN(userIdNum)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "用户ID必须为数字"
            });
        }

        if (targetType && !['video', 'comment'].includes(targetType)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "目标类型必须为video或comment"
            });
        }

        const result = await likesAPI.getUserLikeHistory(userIdNum, targetType, pageNum, limitNum);

        if (!result.success) {
            return res.json({
                code: STATUS_CODES.OPERATION_FAILED.code,
                message: result.message
            });
        }

        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: "获取点赞历史成功",
            data: {
                likes: result.likes,
                pagination: result.pagination
            }
        });
    } catch (error) {
        res.json({
            code: STATUS_CODES.SERVER_ERROR.code,
            message: "获取点赞历史失败：" + error.message
        });
    }
});

/**
 * @route GET /likes/popular/:targetType
 * @description 获取热门内容
 * @param {string} targetType - 目标类型
 * @query {number} timeRange - 时间范围（天数），默认7
 * @query {number} limit - 限制数量，默认20
 */
router.get('/popular/:targetType', async (req, res) => {
    try {
        const { targetType } = req.params;
        const { timeRange = 7, limit = 20 } = req.query;

        // 类型转换和验证
        const timeRangeNum = parseInt(timeRange);
        const limitNum = parseInt(limit);

        if (!['video', 'comment'].includes(targetType)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "目标类型必须为video或comment"
            });
        }

        const result = await likesAPI.getPopularContent(targetType, timeRangeNum, limitNum);

        if (!result.success) {
            return res.json({
                code: STATUS_CODES.OPERATION_FAILED.code,
                message: result.message
            });
        }

        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: "获取热门内容成功",
            data: result.popular
        });
    } catch (error) {
        res.json({
            code: STATUS_CODES.SERVER_ERROR.code,
            message: "获取热门内容失败：" + error.message
        });
    }
});

/**
 * @route DELETE /likes/:userId/:targetType/:targetId
 * @description 删除点赞记录
 * @param {number} userId - 用户ID
 * @param {string} targetType - 目标类型
 * @param {number} targetId - 目标ID
 */
router.delete('/:userId/:targetType/:targetId', async (req, res) => {
    try {
        const { userId, targetType, targetId } = req.params;

        // 类型转换和验证
        const userIdNum = parseInt(userId);
        const targetIdNum = parseInt(targetId);

        if (isNaN(userIdNum) || isNaN(targetIdNum)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "用户ID和目标ID必须为数字"
            });
        }

        if (!['video', 'comment'].includes(targetType)) {
            return res.json({
                code: STATUS_CODES.INVALID_PARAMS.code,
                message: "目标类型必须为video或comment"
            });
        }

        const result = await likesAPI.deleteLike(userIdNum, targetType, targetIdNum);

        if (!result.success) {
            return res.json({
                code: STATUS_CODES.OPERATION_FAILED.code,
                message: result.message
            });
        }

        res.json({
            code: STATUS_CODES.SUCCESS.code,
            message: result.message
        });
    } catch (error) {
        res.json({
            code: STATUS_CODES.SERVER_ERROR.code,
            message: "删除点赞记录失败：" + error.message
        });
    }
});

module.exports = router;